package exam;

// 定义链表节点类
class ListNode {
    int value;
    ListNode next;

    ListNode(int value) {
        this.value = value;
        this.next = null;
    }
}

// 定义单向链表类
class LinkedList {
    ListNode head;

    // 添加节点到链表尾部
    public void append(int value) {
        ListNode newNode = new ListNode(value);
        if (head == null) {
            head = newNode;
        } else {
            ListNode current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 打印链表，不显示最后的null
    public void printList() {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.value);
            if (current.next != null) {
                System.out.print("->");
            }
            current = current.next;
        }
        System.out.println();
    }

    // 反转链表
    public void reverse() {
        ListNode prev = null;
        ListNode current = head;
        ListNode nextNode = null;

        while (current != null) {
            nextNode = current.next; // 保存下一个节点
            current.next = prev;     // 反转当前节点的指针
            prev = current;          // 移动prev指针
            current = nextNode;      // 移动current指针
        }
        head = prev;
    }

    // 主方法用于测试
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.append(1);
        list.append(2);
        list.append(3);
        list.append(4);
        list.append(5);

        System.out.println("原始链表：");
        list.printList();

        list.reverse();

        System.out.println("反转后的链表：");
        list.printList();
    }
}